//
//  DateCollectinView.m
//  TableTest
//
//  Created by 众拳科技 on 2017/11/14.
//  Copyright © 2017年 众拳科技. All rights reserved.
//

#import "DateCollectinView.h"
#import "WeekCollectionViewLayout.h"
#import "DateCollectionViewCell.h"

@interface DateCollectinView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

/**
 记录当前滚动的位置
 */
@property(nonatomic,assign)CGFloat currentPosition;

@end

@implementation DateCollectinView

-(id)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        [self initData];
        
        //顶部日期选择        
        WeekCollectionViewLayout *flowLayout = [[WeekCollectionViewLayout alloc] initWithRowCount:1 itemCountPerRow:1];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        UICollectionView *dateCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        dateCollectionView.showsHorizontalScrollIndicator = false;
        dateCollectionView.backgroundColor = [UIColor whiteColor];
        [dateCollectionView registerClass:[DateCollectionViewCell class] forCellWithReuseIdentifier:@"DateCollectionViewCell"];
        dateCollectionView.userInteractionEnabled = true;
        dateCollectionView.bounces = YES;
        dateCollectionView.pagingEnabled = YES;
        dateCollectionView.delegate = self;
        dateCollectionView.dataSource = self;
        dateCollectionView.allowsMultipleSelection = YES;
        [self addSubview:dateCollectionView];
        self.dateCollectionView = dateCollectionView;
        
        self.currentPosition = 0;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(firstDayOfWeekChange:) name:@"WeekCollectionViewPageScorll" object:nil];
        
        [self setConstraints];
    }
    
    return self;
}


-(void)initData{
    
    NSDate *now = [NSDate date];
    
    self.firstDayOfWeek = [self getFirstWeekDate:now];
    
    [self.dateCollectionView reloadData];
    
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];

    [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSLog(@"星期天开始 %@",[formater stringFromDate:self.firstDayOfWeek]);
//    NSLog(@"当前 %@",[formater stringFromDate:now]);
//    NSLog(@"星期六结束 %@",[formater stringFromDate:lastDayOfWeek]);
    
}

-(void)setConstraints{
    
    [self.dateCollectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(self);
    }];
}

#pragma mark CollectionDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 3;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    DateCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DateCollectionViewCell" forIndexPath:indexPath];
    
    cell.firstDayOfWeek = self.firstDayOfWeek;
    
    return  cell;
}

#pragma mark UICollectionDelete

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if ([self checkNeedScroll:scrollView]) {
        
        NSInteger realIndex = 3 / 2;//移动回第一个
        
        self.currentPosition = realIndex;
        
        NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:realIndex inSection:0];
        
        [self.dateCollectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    }
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSLog(@"scrollViewDidEndDecelerating  -   End of Scrolling.");
    
    CGPoint positionPoint = scrollView.contentOffset;
    
    positionPoint.y = scrollView.center.y;
    
    NSIndexPath *indexPathNow = [self.dateCollectionView indexPathForItemAtPoint:positionPoint];
    
    NSString *dir;
    
    if (indexPathNow.row == self.currentPosition) {
        
        return;
    }
    
    //在这里判断UICollectionView是向右滑动还是向左滑动
    if (indexPathNow.row > self.currentPosition) {

        self.firstDayOfWeek = [self getDayWithDate:self.firstDayOfWeek andDayCount:7];
        
        NSLog(@"x= %f,positionRow = %ld  currentPosition = %f",positionPoint.x,(long)indexPathNow.row,self.currentPosition);
        NSLog(@"向➡️➡️➡️➡️➡️➡️➡️");
        
        dir = @"right";
    }
    else{

        self.firstDayOfWeek = [self getDayWithDate:self.firstDayOfWeek andDayCount:-7];
        
        NSLog(@"x= %f,positionRow = %ld  currentPosition = %f",positionPoint.x,(long)indexPathNow.row,self.currentPosition);
        NSLog(@"向⬅️⬅️⬅️⬅️⬅️⬅️⬅️⬅️");
        
        dir = @"left";
    }

    self.currentPosition = indexPathNow.row;

    CGFloat position = scrollView.contentOffset.x;
    
    CGFloat maxPoisition = scrollView.contentSize.width - self.frame.size.width;
    
    if (position <= 0 || position >= maxPoisition) {
        
        self.currentPosition = 3 / 2;
    }
    
    [self.dateCollectionView reloadData];
    
    //把FirstDayOfWeek 广播出去
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DateCollectionViewPageScorll" object:nil userInfo:@{@"firstDayOfWeek":self.firstDayOfWeek,@"currentPosition": @(self.currentPosition),@"dir":dir}];
}

//检查是否需要重新移动cell
- (BOOL)checkNeedScroll:(UIScrollView *)scrollView {
    
    CGFloat position = scrollView.contentOffset.x;
    
    CGFloat maxPoisition = scrollView.contentSize.width - self.frame.size.width;
    
    return position <= 0 || position >= maxPoisition;
}


#pragma mark 日期视图滑动的通知
-(void)firstDayOfWeekChange:(NSNotification *)sender{
    
    NSDictionary *userInfo = sender.userInfo;
    
    self.firstDayOfWeek = [userInfo objectForKey:@"firstDayOfWeek"];
    
    [self.dateCollectionView reloadData];
}



/**
 根据日期得到一个星期最开始的一天

 @param date 日期
 */
-(NSDate *)getFirstWeekDate:(NSDate *)date{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *comp =[calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekOfMonth fromDate:date];
    
    // 得到星期几
    
    // 0(星期天) 1(星期一) 2(星期二) 3(星期三) 4(星期四) 5(星期五) 6(星期六)
    NSInteger weekDay = [comp weekday] - 1;
    
    // 得到几号
    NSInteger day = [comp day];
    
    // 计算当前日期和这周的星期天和星期六差的天数
    long firstDiff,lastDiff;
    
    if (weekDay == 0) {
        
        firstDiff = 0;
        
        lastDiff = 6;
        
    }else{
        
        firstDiff = [calendar firstWeekday] - weekDay - 1;
        
        lastDiff = 6 - weekDay;
    }
    
    NSLog(@"firstDiff:%ld   lastDiff:%ld",firstDiff,lastDiff);
    
    // 在当前日期(去掉了时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    
    [firstDayComp setDay:day + firstDiff];
    
    NSDate *firstDayOfWeek= [calendar dateFromComponents:firstDayComp];

    return firstDayOfWeek;
    
//    self.firstDayOfWeek = firstDayOfWeek;
//
//    [self.dateCollectionView reloadData];
    
}

-(void)setSelectDate:(NSDate *)selectDate{
    
    _selectDate = selectDate;
    
    NSDate *firstDayOfWeek = [self getFirstWeekDate:selectDate];
    
    NSTimeInterval result = [firstDayOfWeek timeIntervalSinceDate:self.firstDayOfWeek];
    
    if (result == 0) {
        
        return;
    }
    
    self.firstDayOfWeek = firstDayOfWeek;
    
    [self.dateCollectionView reloadData];
    
    NSTimeInterval secs = [selectDate timeIntervalSinceDate:[NSDate date]];
    
    //把FirstDayOfWeek 广播出去
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DateCollectionViewPageScorll" object:nil userInfo:@{@"firstDayOfWeek":self.firstDayOfWeek,@"currentPosition": @(self.currentPosition),@"dir":secs>0?@"right":@"left"}];
}

/**
 根据时间得到是这个时间是每个月的几号
 @param date 时间
 @return 几号
 */
-(NSInteger)getDayWithDate:(NSDate *)date{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *comp =[calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekOfMonth fromDate:date];
    
    // 得到几号
    NSInteger day = [comp day];
    
    return day;
}


/**
 日期的加减计算
 @param date 开始时间
 @param count 距离开始时间的天数
 @return 计算后的日期
 */
-(NSDate *)getDayWithDate:(NSDate *)date andDayCount:(NSInteger)count{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *oldComp =[calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekOfMonth fromDate:date];
    
    NSInteger day = [oldComp day];
    
    [oldComp setDay:day + count];
    
    NSDate *newDate= [calendar dateFromComponents:oldComp];
    
    return newDate;
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
